import re

from django_redis import get_redis_connection
from rest_framework.serializers import ModelSerializer
from .models import *
from rest_framework import serializers


class UserSer(ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class StdUserSerializer(serializers.Serializer):
    nickname = serializers.CharField(max_length=20)
    phone = serializers.CharField(max_length=11)
    password = serializers.CharField(max_length=20)
    password2 = serializers.CharField(max_length=20)
    code = serializers.CharField(max_length=4)

    def validate_nickname(self, value):
        try:
            StdUser.objects.get(nickname=value)
        except StdUser.DoesNotExist:
            return value
        raise serializers.ValidationError({
            "nickname": "该用户名已注册"
        })

    def validate_phone(self, value):
        try:
            StdUser.objects.get(phone=value)
        except StdUser.DoesNotExist:
            return value
        raise serializers.ValidationError({
            "phone": "该手机号已注册"
        })

    def validate_password(self, value):
        print('2')
        if not re.match('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$', value):
            raise serializers.ValidationError({
                "password": "密码必须由8-20个字母和数字组合"
            })
        return value

    def validate(self, data):
        print('1')
        cache = get_redis_connection('verify_code')
        sms_code_cache = cache.get(data['phone'])

        if not data['password'] == data['password2']:
            raise serializers.ValidationError({
                "password": "密码不一致"
            })

        if sms_code_cache is None or data["code"] != sms_code_cache.decode('utf-8'):
            raise serializers.ValidationError({
                "sms_code": "短信验证码错误"
            })
        cache.delete(data['phone'])

        return data

    def create(self, validated_data):
        user = StdUser.objects.create(
            nickname=validated_data['username'],
            password=validated_data['password'],
            phone=validated_data['phone'],
        )
        user.password(validated_data['password'])
        user.save()
        return user


class UserRegEmailSer(serializers.Serializer):
    """邮件注册序列化"""
    nickname = serializers.CharField(max_length=50)
    email = serializers.CharField(max_length=200)
    password = serializers.CharField(max_length=200)

    def validate_email(self, value):
        # 判断是否已注册
        try:
            User.objects.get(email=value)
        except User.DoesNotExist:
            return value
        raise serializers.ValidationError({'email': '该邮箱已注册'})

    def validate_password(self, value):
        if not re.match('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{8,20}$', value):
            raise serializers.ValidationError({'password': '密码必须由8-20个字母和数字组成'})
        return value

    def validate_nickname(self, value):
        return value
